package com.zhongxi.guoyuan.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.CategoryAdapter;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.adapter.ad.JDViewAdapter;
import com.zhongxi.guoyuan.adapter.coinShop.CoinAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.coinStore.CoinStoreData;
import com.zhongxi.guoyuan.entity.coinStore.CoinStoreResult;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MoreAdActivity;
import com.zhongxi.guoyuan.view.coinShopping.CoinCategoryActivity;
import com.zhongxi.guoyuan.view.coinShopping.CoinShoppingDetailActivity;
import com.zhongxi.guoyuan.view.coinShopping.CoinStoreListActivity;
import com.zhongxi.guoyuan.view.coinShopping.NewGoodsActivity;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.ViewFlowIndicator;
import com.zhongxi.guoyuan.widget.ad.JDAdverView;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.util.ArrayList;
import java.util.List;


public class MainCoinFragment extends BaseFragment implements View.OnClickListener, MyScrollView.OnScrollListener {

    private ViewFlow viewflow;
    List<CoinStoreData> myData = new ArrayList<CoinStoreData>();
    private ImageBannerAdapter mBannerAdapter;
    private NoScrollGridView gv_category;
    private LinearLayout linearLayout;
    private RelativeLayout relaBegin;
    private RelativeLayout relaScrollBody;
    private LinearLayout linearStop;
    private MyScrollView myScrollView;
    private boolean isMeasured;
    private int mScrollHeight;
    private Spinner spinner;
    private RelativeLayout linearShop;
    private RelativeLayout linearNew;
    private String type;
    private NoScrollListView lvList;
    private CoinAdapter coinAdapter;
    private ImageView ivNew;
    private TextView tvNewGoodsName;
    private TextView tvNewGoodsDesc;
    private TextView tvNewGoodsCoin;
    private ImageView ivShop;
    private TextView tvStoreName;
    private TextView tvStoreDesc;
    private TextView tvStoreView;
    private RatingBar rb;
    private View viewMore;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_forth, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("银币消费商家");
        linearShop = (RelativeLayout) getView().findViewById(R.id.linearShop);
        linearNew = (RelativeLayout) getView().findViewById(R.id.lineNew);
        lvList = (NoScrollListView) getView().findViewById(R.id.lvList);
        gv_category = (NoScrollGridView) getView().findViewById(R.id.gv_category);
        //上拉悬停
        initScrollPause();
        //今日新品
        ivNew = (ImageView) getView().findViewById(R.id.ivNew);
        tvNewGoodsName = (TextView) getView().findViewById(R.id.tvNewGoodsName);
        tvNewGoodsDesc = (TextView) getView().findViewById(R.id.tvNewGoodsDesc);
        tvNewGoodsCoin = (TextView) getView().findViewById(R.id.tvNewGoodsCoin);
        //口碑商家
        ivShop = (ImageView) getView().findViewById(R.id.ivShop);
        tvStoreName = (TextView) getView().findViewById(R.id.tvStoreName);
        tvStoreDesc = (TextView) getView().findViewById(R.id.tvStoreDesc);
        tvStoreView = (TextView) getView().findViewById(R.id.tvStoreView);

        viewMore = (View) getView().findViewById(R.id.viewMore);

        rb = (RatingBar) getView().findViewById(R.id.rb);
        //智能排序
        order();
        //设置高度
        FrameLayout flow = (FrameLayout) getView().findViewById(R.id.flow);
        ImageUtils.setHeight(getActivity(), Constants.flowRate, flow);
    }

    //智能排序
    private void order() {
        spinner = (Spinner) getView().findViewById(R.id.spinner);
        ArrayAdapter<String> spAdapter = new ArrayAdapter<String>(context, R.layout.simple_spinner_item);
        List<String> spList = new ArrayList<String>();
        spList.add("离我最近");
        spList.add("点赞率最高");
        spAdapter.addAll(spList);
        spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spAdapter);

        coinAdapter = new CoinAdapter(context, myData);
        lvList.setAdapter(coinAdapter);
    }

    /**
     * 上拉悬停初始化
     */
    private void initScrollPause() {
        linearLayout = (LinearLayout) getView().findViewById(R.id.linearLayout);
        relaBegin = (RelativeLayout) getView().findViewById(R.id.relaBegin);
        relaScrollBody = (RelativeLayout) getView().findViewById(R.id.relaScrollBody);
        linearStop = (LinearLayout) getView().findViewById(R.id.linearStop);
        myScrollView = (MyScrollView) getView().findViewById(R.id.myScrollView);

        ViewTreeObserver observer = linearLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    mScrollHeight = linearLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
        myScrollView.setOnScrollListener(this);
    }

    /**
     * 上下轮播
     * @param data
     */
    private void initJDScroll(List<HotGoodsData> data) {

        final JDViewAdapter jddapter = new JDViewAdapter(context, data, 2);
        final JDAdverView tbView = (JDAdverView) getView().findViewById(R.id.jdadver);
        tbView.setAdapter(jddapter);
        //开启线程滚动
        tbView.start();
    }

    /**
     * 左右轮播
     * @param data
     */
    private void initViewFlow(List<AdData> data) {
        /**
         * 轮播
         */
        viewflow = (ViewFlow) getView().findViewById(R.id.viewflow);
        ViewFlowIndicator viewflowdic = (ViewFlowIndicator) getView().findViewById(R.id.viewflowdic);
        viewflow.setFlowIndicator(viewflowdic);

        if(data.size()>0)
            viewflow.setSideBuffer(data.size()); // 实际图片数量
        if(mBannerAdapter == null){
            mBannerAdapter = new ImageBannerAdapter(getActivity(), data);
            viewflow.setAdapter(mBannerAdapter);
        }else{
            mBannerAdapter.replaceAll(data);
        }
        viewflow.startAutoFlowTimer();
    }

    /**
     * 获取数据
     */
    @Override
    protected void initData() {
        super.initData();
        //获取广告
        showAds();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        linearNew.setOnClickListener(this);
        viewMore.setOnClickListener(this);
        gv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(context, CoinCategoryActivity.class);
                intent.putExtra("position", position);
                startActivity(intent);
            }
        });
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(context, CoinShoppingDetailActivity.class);
                intent.putExtra("shopid", myData.get(position).getId());
                startActivity(intent);
            }
        });
        linearShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAct(CoinStoreListActivity.class);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.viewMore:
                startActivity(new Intent(context, MoreAdActivity.class));
                break;
            case R.id.lineNew:
                startAct(NewGoodsActivity.class);
                break;
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("showads".equals(type)){
                AdResult adResult = gson.fromJson(response, AdResult.class);
                MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                if(adResult.getData().size()>0)
                initViewFlow(adResult.getData());
                //获取商品分类列表
                getCategory();
            }else if("category".equals(type)){
                ProjectItemResult itemResult = gson.fromJson(response, ProjectItemResult.class);
                MyApplication.getInstance().setSpValue(itemResult.getSafeobj());
                setCategory(itemResult.getData());
                //获取爆品
                getHotGoods();
            }else if("hotGoods".equals(type)){
                HotGoodsResult hotResult = gson.fromJson(response, HotGoodsResult.class);
                MyApplication.getInstance().setSpValue(hotResult.getSafeobj());
                if(hotResult.getData().size()>0)
                    initJDScroll(hotResult.getData());
                //获取今日新品
                getNewGoods();
            }else if("newGoods".equals(type)){
                HotGoodsResult hotResult = gson.fromJson(response, HotGoodsResult.class);
                MyApplication.getInstance().setSpValue(hotResult.getSafeobj());
                if(hotResult.getData().size()>0)
                    initNewGoods(hotResult.getData().get(0));
                //获取口碑商家上下轮播
                getStore();
            }else if("getStore".equals(type)){
                CoinStoreResult storeResutlt = gson.fromJson(response, CoinStoreResult.class);
                MyApplication.getInstance().setSpValue(storeResutlt.getSafeobj());
                if(storeResutlt.getData().size()>0)
                    initStoreData(storeResutlt.getData().get(0));
                //获取商家列表
                getShopList();
            }else if("getshoplist".equals(type)){
                CoinStoreResult shopResult = gson.fromJson(response, CoinStoreResult.class);
                MyApplication.getInstance().setSpValue(shopResult.getSafeobj());
                if(shopResult.getData().size()>0){
                    myData.addAll(shopResult.getData());
                }
                coinAdapter.notifyDataSetChanged();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
    }

    /**
     * 初始化口碑商家数据
     * @param coinStoreData
     */
    private void initStoreData(CoinStoreData coinStoreData) {
        if(null!=coinStoreData){
            if(null!=coinStoreData.getName()&&!"".equals(coinStoreData.getName())){
                tvStoreName.setText(coinStoreData.getName());
            }else{
                tvStoreName.setText("");
            }
            if(null!=coinStoreData.getSubject()&&!"".equals(coinStoreData.getSubject())){
                tvStoreDesc.setText(coinStoreData.getSubject());
            }else{
                tvStoreDesc.setText("");
            }
            if(null!=coinStoreData.getViewnum()&&!"".equals(coinStoreData.getViewnum())){
                tvStoreView.setText(coinStoreData.getViewnum());
            }else{
                tvStoreView.setText("");
            }
            if(null!=coinStoreData.getThumbnail()&&!"".equals(coinStoreData.getThumbnail())){
                Glide.with(context).load(Url.IMG_URL+coinStoreData.getThumbnail()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivShop);
            }
            if(null!=coinStoreData.getStarlevel()&&!"".equals(coinStoreData.getStarlevel())){
                rb.setRating(Float.parseFloat(coinStoreData.getStarlevel()));
            }else{
                rb.setRating(5);
            }
        }
    }

    /**
     * 初始化今日新品数据
     * @param hotGoodsData
     */
    private void initNewGoods(HotGoodsData hotGoodsData) {
        if(null!=hotGoodsData){
            if(null!=hotGoodsData.getName()&&!"".equals(hotGoodsData.getName())){
                tvNewGoodsName.setText(hotGoodsData.getName());
            }else{
                tvNewGoodsName.setText("");
            }
            if(null!=hotGoodsData.getSubject()&&!"".equals(hotGoodsData.getSubject())){
                tvNewGoodsDesc.setText(hotGoodsData.getSubject());
            }else{
                tvNewGoodsDesc.setText("");
            }
            if(null!=hotGoodsData.getThumbnail()&&!"".equals(hotGoodsData.getThumbnail())){
//                ImageLoader.getInstance().displayImage(Url.IMG_URL+hotGoodsData.getThumbnail(), ivNew, CommonTool.getOptions(R.mipmap.iv_eg));
                Glide.with(context).load(Url.IMG_URL+hotGoodsData.getThumbnail()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 10)).centerCrop().into(ivNew);
            }
            if(null!=hotGoodsData.getPrice()&&!"".equals(hotGoodsData.getPrice())){
                tvNewGoodsCoin.setText(hotGoodsData.getPrice());
            }else{
                tvNewGoodsCoin.setText("");
            }
        }
    }

    /**
     * 添加分类列表
     * @param data
     */
    private void setCategory(List<ProjectItemData> data) {
        CategoryAdapter adapter = new CategoryAdapter(getActivity(), data);
        gv_category.setAdapter(adapter);
    }

    private void getNewGoods() {
        type = "newGoods";
        getServer(Url.NEW_GOODS, null, "", false, null, "get");
    }

    private void getHotGoods() {
        type = "hotGoods";
        getServer(Url.HOT_GOODS, null, "", false, null, "get");
    }

    /**
     * 获取商品分类列表
     */
    private void getCategory() {
        type = "category";
        getServer(Url.CATEGORY_LIST, null, "", false, null, "get");
    }

    /**
     * 获取广告展示
     */
    private void showAds() {
        type = "showads";
        String getStr = "&type=3";
        getServer(Url.SHOW_ADS, null,getStr, false, null, "get");
    }

    /**
     * 获取店铺列表
     */
    private void getShopList() {
        type = "getshoplist";
        String str = "&page=" + pageNum + "&lng="+MyApplication.getInstance().getLongitude()+"&lat="+MyApplication.getInstance().getLatitude()+"&orderby=0";
        Log.i("base", str);
        getServer(Url.COIN_SHOP_LIST, null, str, false, null, "get");
    }

    /**
     * 获取口碑商家上下轮播
     */
    private void getStore() {
        type = "getStore";
        getServer(Url.REPUTATION_STORE, null, "", false, null, "get");
    }

    @Override
    public void onScroll(int scrollY) {
        if(scrollY >= mScrollHeight){
            if(relaScrollBody.getParent() != linearStop){
                relaBegin.removeView(relaScrollBody);
                linearStop.addView(relaScrollBody);
            }
        }else{
            if(relaScrollBody.getParent() != relaBegin){
                linearStop.removeView(relaScrollBody);
                relaBegin.addView(relaScrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (!MyTextUtils.isFastDoubleClick()) {
            pageNum++;
            getShopList();
        }
    }

}
